<template>
  <div v-loading="loading" class="uploaderWrapper">
    <div class="m-dialog-wrap">
      <div class="content">
        <div class="videoTItle">
          <i>*</i>
          推荐采用mp4格式，可有效缩短转码耗时。支持视频大小100MB以内的视频，建议时长5分钟或以内的视频
        </div>
        <div class="uploadContent">
          <div class="uploadArea">
            <input
              v-show="false"
              id
              ref="uploadWidget"
              required
              type="file"
              name
              @change="upload"
            />
            <div v-if="!infoId && percentComplete == 0" @click="doUpload">
              <span v-if="percentComplete == 0">+</span>
            </div>

            <!-- :src="videoSrcPath" -->
            <!-- :src="serveUrl + '/bnd-video/fileHandler/download/video/' + infoId" -->
            <div v-if="infoId" style="width:100%;height:100%">
              <video
                style="width:100%;height:100%"
                :src="serveUrl + '/bnd-video/fileHandler/download/video/' + infoId"
                muted
                controls
                playsinline
                x5-video-player-type="h5"
                name="media"
                data-video="0"
              ></video>
            </div>
          </div>
          <div class="progress-line" style="margin-top:10px;">
            <el-progress
              v-if="percentComplete > 0"
              style="width:300px"
              :text-inside="true"
              :stroke-width="16"
              :percentage="percentComplete"
            ></el-progress>
          </div>

          <span v-if="infoId" class="tips" @click="doUpload">重新上传</span>
          <div class="videoDoc">
            <p>横板视频:</p>
            <p>建议上传16：9，分辨率1280*720及以上视频</p>
            <p class="line-tab">竖版视频:</p>
            <p>建议上传9：16，分辨率720*1280及以上视频</p>
          </div>
        </div>
      </div>

      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        style="padding: 26px;"
        label-position="right"
        label-width="120px"
      >
        <el-form-item label=" 视频名称: " prop="name">
          <el-input
            v-model="ruleForm.name"
            type="textarea"
            :rows="3"
            resize="none"
            maxlength="50"
            style="width: 390px;"
            show-word-limit
            placeholder="请输入视频名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="类型:" prop="type">
          <el-checkbox-group v-model="ruleForm.type" @change="ladderChange">
            <el-checkbox
              v-for="item in radios"
              :key="item.key"
              :label="item.value"
              name="type"
            ></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="选择分组:" prop="groupId">
          <el-select v-model="ruleForm.groupId" placeholder="请选择" style="width: 390px;">
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="简介:" prop="introduce">
          <el-input
            v-model="ruleForm.introduce"
            type="textarea"
            :rows="9"
            maxlength="500"
            show-word-limit
            placeholder="请输入内容"
            style="width: 390px;"
            resize="none"
            class="content-textarea"
          ></el-input>
        </el-form-item>

        <el-form-item class="submit-btn">
          <el-button class="cancle-btn" @click="closeDialog('ruleForm')">取消</el-button>
          <el-button type="primary" @click="onOK('ruleForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex';
  // import { getToken } from '@/utils/auth';
  import {
    fetchOSS,
    getBussinessLineGroup,
    addVideoMessage,
    updateVideoMessage,
    getVideoMessage,
    toAudit,
  } from '@/api/uploaderCenter';

  export default {
    name: 'Uploader',
    props: {
      isVisible: {
        type: Boolean,
        default: false,
      },
      editData: {
        type: Object,
        default() {
          return {};
        },
      },
    },
    data() {
      return {
        ruleForm: {
          name: '',
          businessLineId: '',
          merchantId: '',
          type: ['无'],
          groupId: '',
          introduce: '',
        },
        // 表单校验
        rules: {
          name: [{ required: true, message: '请输入视频名称', trigger: 'blur' }],
          businessLineId: [{ required: true, message: '请选择所属业务线', trigger: 'change' }],
          groupId: [{ required: true, message: '请选择分组', trigger: 'change' }],
          type: [{ type: 'array', required: true, message: '请选择视频类型', trigger: 'change' }],
        },
        showMask: false,
        fileWidth: null,
        fileHeight: null,
        file: '',
        fileName: '',
        fileType: '',
        fileSize: '',
        accessid: '',
        callback: '',
        policy: '',
        signature: '',
        expire: 0,
        now: Date.parse(new Date()) / 1000,
        host: 'http://oss.aliyuncs.com',
        infoId: '',
        // 表单开始
        radios: [
          { key: -1, value: '无' },
          { key: 0, value: '自制' },
          { key: 1, value: '转载' },
        ],
        typeList: [],
        storeList: [],
        // businessLineArr: [],
        editShowData: null,
        duration: '', // 视频时长
        // 图片上传
        imgurl: `/bnd-video/fileHandler/info/image`,
        imageUrl: '',
        isEnterprise: null, // 是否企业对接
        isBusinessButt: null, // 是否业务线对接
        percentComplete: 0, // 视频上传进度
        videoType: ['video/mp4'],
        title: '上传素材',
        loading: false,
        getBusinessLoading: false,
        serveUrl: '',
        videoSrcPath: '',
      };
    },
    computed: {
      ...mapGetters('user', ['userInfo']),
      userLot() {
        return this.userInfo;
      },
      isClient() {
        return !!this.userInfo.isClient || false;
      },
    },
    watch: {
      editData: {
        deep: true, // 深度监听
        immediate: true, // 立即监听
        handler: function(newV) {
          if (newV && newV.id) {
            this.setEditForm(newV);
          }
        },
      },
    },
    async created() {
      this.serveUrl =
        process.env.NODE_ENV === 'development'
          ? 'https://dev.shanglike.com'
          : `${window.location.protocol}//${window.location.host}`;
      this.ruleForm.businessLineId = 4;
      const hasToken = await this.getUrlMatch();
      if (this.ruleForm.businessLineId && !hasToken) {
        this.getbussinessList();
      }
    },
    methods: {
      ladderChange() {
        if (this.ruleForm.type.length > 1) {
          this.ruleForm.type.shift();
        }
      },
      random_string() {
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = chars.length;
        var pwd = '';
        for (let i = 0; i < 16; i++) {
          pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
      },
      async getbussinessList() {
        console.log(typeof this.ruleForm.businessLineId);
        if (
          this.ruleForm.businessLineId === null ||
          !this.ruleForm.businessLineId ||
          this.ruleForm.businessLineId === 'undefined'
        ) {
          return;
        }
        const res = await getBussinessLineGroup(this.ruleForm.businessLineId);
        if (res && res.status && res.status == 200) {
          this.typeList = res.data;
        }
      },
      async get_signature(type) {
        if (type !== 'image') {
          this.timeOut = setInterval(() => {
            if (this.percentComplete < 99) {
              this.percentComplete += 1;
            }
          }, 80);
        }
        // 可以判断当前expire是否超过了当前时间， 如果超过了当前时间， 就重新取一下，3s 作为缓冲。
        // 图片视频共用一个接口，可能没办法等了。
        // this.now = Date.parse(new Date()) / 1000;
        // if (this.expire < this.now + 3) {
        const data = await fetchOSS({}, type);
        this.accessid = data && data.accessid;
        this.callback = data && data.callback;
        this.host = data && data.host;
        this.dir = data && data.dir;
        this.policy = data && data.policy;
        this.signature = data && data.signature;
        this.expire = parseInt(data && data.expire);
        return true;
        // }
        // return false
      },
      async set_upload_param(type) {
        await this.get_signature(type);
        // g_object_name = key;
        /* if (filename != '') { suffix = get_suffix(filename)
           calculate_object_name(filename)
       } */
        const new_multipart_params = {
          // 'key' : g_object_name,
          policy: this.policy,
          OSSAccessKeyId: this.accessid,
          success_action_status: '200', //让服务端返回200,不然，默认会返回204
          callback: this.callback,
          signature: this.signature,
        };
        return {
          url: '/uploadOSS',
          multipart_params: new_multipart_params,
          file: this.file,
        };
      },
      doUpload() {
        this.$refs.uploadWidget.click();
      },
      deleteVideo() {
        this.infoId = null;
      },
      async uploading(file, type) {
        await this.set_upload_param(type);
        return new Promise(async resolve => {
          const formdata = new FormData();
          const inputDOM = this.$refs.uploadWidget;

          // 通过DOM取文件数据
          if (file) {
            this.fileName = file.name;
          }
          const fileExt = this.file.name.substring(this.file.name.lastIndexOf('.'));
          formdata.append('name', this.fileName);
          formdata.append(
            'key',
            this.dir + this.random_string(16) + new Date().getTime() + fileExt
          ); // this.dir + this.random_string(16)
          formdata.append('policy', this.policy);
          formdata.append('OSSAccessKeyId', this.accessid);
          formdata.append('success_action_status', 200);
          formdata.append('callback', this.callback);
          formdata.append('signature', this.signature);
          if (type === 'image') {
            formdata.append('file', file);
          } else {
            this.fileSize = (inputDOM.files[0].size / 1024 / 1024).toFixed(2);
            if (this.fileSize > 100) {
              this.$notify({
                message: '上传视频大小超过100M限制！',
                type: 'warning',
              });
              clearInterval(this.timeOut);
              this.percentComplete = 0;
              return;
            }
            formdata.append('x:meassure', `${this.fileWidth}*${this.fileHeight}`);
            formdata.append('x:playtime', this.duration || 0 + '');
            let _flie = inputDOM.files[0];
            if (this.isClient) {
              const { electronReadFile } = require('@/utils/electronUpload');
              _flie = await electronReadFile(_flie.path);
              console.log(_flie, '---------------');
            }

            // formdata.append('file', inputDOM.files[0]);
            formdata.append('file', _flie);
          }
          var xmlhttp = null;
          if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
          } else if (window.ActiveXObject) {
            // xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
          }

          if (xmlhttp != null) {
            let that = this;

            // serverUrl是 用户获取 '签名和Policy' 等信息的应用服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
            // const serverUrl = this.host
            xmlhttp.open('post', '/uploadOSS', true); // this.host  '/uploadOSS'
            xmlhttp.send(formdata);
            if (type !== 'image') {
              // 统计上传进度
              xmlhttp.addEventListener('progress', function(event) {
                // 只执行一次，不知道怎么回事
                if (event && event.lengthComputable) {
                  clearInterval(that.timeOut);
                  that.percentComplete = 100;
                  // that.percentComplete = (event.loaded / event.total) * 100;
                }
              });
            }
            xmlhttp.onload = function() {
              if (this.status === 200) {
                resolve(xmlhttp.response);
              }
            };
            return xmlhttp.response;
          } else {
            alert('Your browser does not support XMLHTTP.');
          }
        });
      },
      upload() {
        let inputDOM = this.$refs.uploadWidget;
        // 通过DOM取文件数据
        this.file = inputDOM.files[0];
        if (inputDOM.files[0] === undefined) {
          this.fileName = '';
          this.fileSize = '';
          this.fileType = '';
          // this.$message.error('上传失败');
          return;
        } else {
          if (this.videoType.indexOf(this.file.type) < 0) {
            this.$message({
              message: '请正确上传视频格式',
              type: 'error',
              offset: 80,
            });
            return;
          }
          this.fileName = this.file.name;
          //kb
          if (this.file.size / 1024 < 1000) {
            this.fileSize = (this.file.size / 1024).toFixed(2) + 'kb';
          } else if (this.file.size / 1024 > 1000) {
            this.fileSize = (this.file.size / 1024 / 1024).toFixed(2) + 'MB';
          }
          this.fileType = this.file.type;
          // 获取上传的视频的宽高
          var videoUrl = URL.createObjectURL(inputDOM.files[0]);
          var videoObj = document.createElement('video');
          videoObj.src = videoUrl;
          // 获取视频的长度
          // var duration;
          var that = this;
          videoObj.addEventListener('loadedmetadata', function() {
            // duration = videoObj.duration;
            that.getOOSUploadVIdeoUrl(this.videoWidth, this.videoHeight, this.duration);
            videoObj = null;
          });
        }
      },
      // 上传视频
      getOOSUploadVIdeoUrl(width, height, duration) {
        console.log(width, height, '-------------width height');
        this.fileWidth = width;
        this.fileHeight = height;
        this.duration = duration;

        this.uploading().then(res => {
          const data = res && JSON.parse(res);
          if (data.data && data.status === 200) {
            this.percentComplete = 0;
            this.infoId = data.data.id;
            this.$refs.uploadWidget.value = '';
          }
        });
      },
      // 上传视频弹框关闭
      closeDialog(type) {
        this.loading = false;
        if (type === 'close') {
          // 保存成功后直接关闭，不需要弹出确定框
          this.closeDialogCallback();
          return;
        }
        this.$confirm('取消后信息不保存，确认取消？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.closeDialogCallback();
          })
          .catch(() => {});
      },
      closeDialogCallback() {
        this.$emit('isVisible.sync', false);
        this.editShowData = null;
        this.infoId = '';
        this.imageUrl = '';
        this.$emit('formData', false);
        this.loading = false;
        this.isEnterprise = null;
        this.isBusinessButt = null;
        this.$refs.ruleForm.resetFields();
        for (var key in this.ruleForm) {
          if (this.ruleForm.hasOwnProperty(key)) {
            this.ruleForm[key] = '';
            this.ruleForm['type'] = ['无'];
          }
        }
      },
      // 新增 清空
      resetForm() {
        this.editShowData = null;
        this.infoId = '';
        this.imageUrl = '';
        this.$refs.ruleForm.resetFields();
        for (var key in this.ruleForm) {
          if (this.ruleForm.hasOwnProperty(key)) {
            this.ruleForm[key] = '';
          }
        }
      },
      getUrlMatch() {
        if (!this.isVisible) {
          // sessionStorage.setItem('AccessToken', getToken());
          this.getbussinessList();
          return true;
        }
        return false;
      },

      // 上传视频弹框确定
      onOK(formName) {
        console.log(this.ruleForm);
        // 注意
        // this.infoId = 6;
        if (!this.infoId) {
          this.$message({
            message: '请上传视频',
            type: 'error',
            offset: 80,
          });
          return;
        }
        this.$refs[formName].validate(valid => {
          if (valid) {
            // this.ruleForm.merchantId = this.userLot.organId;
            // this.ruleForm.merchantName = this.userLot.organName;
            let ruleForm = JSON.parse(JSON.stringify(this.ruleForm));
            ruleForm.type =
              ruleForm.type[0] == '无'
                ? -1
                : ruleForm.type[0] == '自制'
                ? 0
                : ruleForm.type[0] == '转载'
                ? 1
                : '';
            const obj = {
              ...ruleForm,
              layoutType: this.fileWidth > this.fileHeight ? 0 : 1,
              businessLineId: 4,
              infoId: this.infoId,
              saveType: 1,
            };
            this.loading = true;
            if (this.editShowData && this.editShowData.id) {
              // 编辑上传公用一个接口
              obj.id = this.editShowData.id;
              updateVideoMessage(obj).then(res => {
                if (res && res.status === 200) {
                  this.loading = false;
                  this.editShowData = null;
                  let videoSize = res.data.measure.split('*');
                  this.closeDialog('close');
                  this.$emit('getVideoInfo', {
                    videoId: res.data.id,
                    videoPath: res.data.videoPath,
                    width: videoSize[0],
                    height: videoSize[1],
                    smallPicPath: res.data.imgPath,
                  });
                  toAudit({
                    businessInfoId: res.data.id,
                    type: 'pass',
                  }).then(result => {
                    if (result.status == 200) {
                      this.$message({
                        message: '编辑成功',
                        type: 'success',
                        offset: 80,
                      });
                    }
                  });
                } else {
                  this.loading = false;
                }
              });
              return;
            }
            // 普通新增
            addVideoMessage(obj).then(res => {
              if (res && res.status === 200) {
                this.loading = false;
                this.closeDialog('close');
                let videoSize = res.data.measure.split('*');
                this.$emit('getVideoInfo', {
                  videoId: res.data.id,
                  videoPath: res.data.videoPath,
                  width: videoSize[0],
                  height: videoSize[1],
                  smallPicPath: res.data.imgPath,
                });
                toAudit({
                  businessInfoId: res.data.id,
                  type: 'pass',
                }).then(result => {
                  if (result.status == 200) {
                    this.$message({
                      message: '新增成功',
                      type: 'success',
                      offset: 80,
                    });
                  }
                });
              } else {
                this.loading = false;
              }
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      // 编辑回填数据
      setEditForm(newName) {
        this.loading = true;
        this.editShowData = newName;
        this.$nextTick(() => {
          this.$refs.ruleForm.resetFields();
          for (var key in this.ruleForm) {
            if (this.ruleForm.hasOwnProperty(key)) {
              this.ruleForm[key] = '';
              this.ruleForm['type'] = ['无'];
            }
          }
          this.loading = false;
          getVideoMessage(newName.id).then(res => {
            if (res && res.status == 200) {
              console.log(res);
              let data = res.data;
              this.infoId = data.videoId;
              this.ruleForm = {
                name: data.videoName,
                businessLineId: `${data.businessLineId}`,
                // merchantId: data.merchantId,
                type:
                  data.type == -1
                    ? ['无']
                    : data.type == 0
                    ? ['自制']
                    : data.type == 1
                    ? ['转载']
                    : '',
                groupId: data.groupId,
                introduce: data.introduce,
              };
              this.title = '编辑素材';
              this.getbussinessList();
            }
          });
        });
      },
    },
  };
</script>

<style lang="scss" scoped>
  @import '~@/styles/mixin.scss';
  .uploaderWrapper {
    .m-dialog-mask {
      @include modalbg();
      position: fixed;
      overflow: auto;
      z-index: 1999;
      top: 0;
      right: 0;
      left: 0;
      bottom: 0;
      outline: 0;
      @include fct();
      background: rgba(0, 0, 0, 0.1);
      z-index: 1999;
    }
    .m-dialog-wrap {
      width: 100%;
      .content {
        padding: 0 20px;
        box-sizing: border-box;
      }
      .uploadArea {
        @include wh(222px, 114px);
        border-radius: 8px;
        @include fct();
        background-color: #f7f6f9;
        margin-top: 14px;
        cursor: pointer;
        > div {
          @include wh(100%, 100%);
          @include fct();
          input {
            @include wh(100%, 100%);
          }
          span {
            @include font(13px, #cacacc, 500);
          }
        }
      }
      .tips {
        @include font(14px, #3770eb, 800);
        margin-top: 14px;
        display: block;
      }
      .videoTItle {
        @include font(14px, #7f848b, 400);
        line-height: 20px;
        i {
          @include font(13px, #e66574, 800);
        }
      }
      .videoDoc {
        margin-top: 13px;
        @include font(14px, #7f848b, 400);
        p {
          line-height: 24px;
          margin: 0;
          padding: 0;
        }
        .line-tab {
          margin-top: 10px;
        }
      }
      /deep/.el-checkbox__input.is-checked .el-checkbox__inner {
        border-radius: 50%;
        background-color: #3770eb;
        border-color: #3770eb;
      }
      /deep/.el-checkbox__inner {
        border-radius: 50%;
      }
      /deep/.el-form-item__content {
        display: flex;
        flex-direction: column;
        margin-left: 0 !important;
      }
      /deep/.el-form-item__label {
        width: 90px !important;
        text-align: right;
        @include font(14px, #7f848b, 400);
      }
      /deep/.el-form {
        padding: 0 !important;
        margin-top: 20px;
      }
      .content-textarea {
        border-radius: 7px;
        /deep/.el-textarea__inner {
          background-color: #f7f6f9;
        }
        /deep/.el-input__count {
          @include font(10px, #b4b8be, 400);
          background-color: #f7f6f9;
        }
      }
      .submit-btn {
        width: 100%;
        /deep/.el-form-item__content {
          width: 100%;
          display: flex;
          flex-direction: row;
          justify-content: flex-end;
        }
        button {
          @include wh(100px, 40px);
          border-radius: 7px;
          border: 2px solid #e8e4e8;
        }
      }
      .upload {
        height: 80px;
      }
    }
  }
</style>
